package com.llpy.Service;

import com.llpy.Utils.GridFSUtils;
import com.mongodb.client.gridfs.GridFSBucket;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

@Service
public class MusicService {
    private final GridFSUtils gridFSUtils;

    @Autowired
    public MusicService(GridFSUtils gridFSUtils) {
        this.gridFSUtils = gridFSUtils;
    }



    //创建一个名为music的存储桶
    public GridFSBucket getGridFSBucket(){
        return gridFSUtils.getGridFSBucket("music");
    }

    //删除音频
    public void deleteMusic(ObjectId id){
        gridFSUtils.getGridFSBucket("music").delete(id);
    }

    //读取音频
    public void getMusic(String fileId, ByteArrayOutputStream outputStream) {
        getGridFSBucket().downloadToStream(new ObjectId(fileId),outputStream);
    }


    //保存音频文件
    public ObjectId saveMusic(MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();
        System.out.println(file.getContentType());
        InputStream inputStream = file.getInputStream();
        assert fileName != null;
        return getGridFSBucket().uploadFromStream(fileName, inputStream);
    }
}
